package sp.servlet;

import sp.entity.User;
import sp.service.UserService;
import sp.service.UserServiceImpl;
import sp.util.ParamUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        User user = new User(req.getParameter("userName"),req.getParameter("password"));
        String resultFormat = "{\"state\":\"%b\",\"error\":\"%s\"}";
        String result = "";
        try {
            List<User> users = userService.find(user);
            if(users!=null) {
                if (users.size() == 0) result = String.format(resultFormat, false, "账号或密码错误!!!");
                else if(users.get(0).getType()>2) result = String.format(resultFormat, false, "非管理员账号!!!");
                else result  = String.format(resultFormat,true,"");
            }

        } catch (RuntimeException e){
            result  = String.format(resultFormat,false,e.getMessage());
        }
        resp.getWriter().write(result);
        resp.flushBuffer();
    }
}
